package com.wswy.wzcx.ui.user

import android.support.design.widget.TextInputEditText
import android.support.design.widget.TextInputLayout
import android.text.Editable
import android.text.TextUtils
import android.view.View
import android.widget.ImageView
import com.wswy.wzcx.R
import com.wswy.wzcx.ui.other.PhoneTextWatcher
import com.wswy.wzcx.ui.other.TextWatcherIMPL

class PhoneLayoutController(
        private val layoutPhone: TextInputLayout,
        private val etPhone: TextInputEditText,
        private val imgPhoneAction:ImageView

) {

    init {

        //清除输入框
        imgPhoneAction.setOnClickListener {

            etPhone.text = null

            imgPhoneAction.visibility = View.GONE

        }
        etPhone.addTextChangedListener(PhoneTextWatcher(etPhone))

        etPhone.addTextChangedListener(object : TextWatcherIMPL(){
            override fun afterTextChanged(s: Editable?) {
                super.afterTextChanged(s)
                if (!TextUtils.isEmpty(s)){
                    imgPhoneAction.visibility = View.VISIBLE
                }else{
                    imgPhoneAction.visibility = View.GONE
                }
                inputCheck()
            }
        })


    }

    private fun inputCheck(){


        val text = PhoneTextWatcher.getRealPhoneNumber(etPhone)

        //手机号输入正确
        val phone = !TextUtils.isEmpty(text) && text?.length == 11

        layoutPhone.error = null

        if (phone){
            imgPhoneAction.isClickable = false
            imgPhoneAction.setImageResource(R.drawable.login_ok)

        }else{

            if (text?.length?:0 > 0){
                imgPhoneAction.isClickable = true
                imgPhoneAction.setImageResource(R.drawable.ic_clean)
            }else{
                imgPhoneAction.isClickable = false
                imgPhoneAction.setImageResource(0)
            }
        }

    }
}